<?php

namespace App\Http\Controllers\Home;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\Option;
use App\Models\Commission;
//use App\Models\UserRelationship;
use App\User;
use Validator,Config;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB; 
use App\Repositories\MemberRepositoryEloquent;
class OrderController extends Controller{

    protected $user;

    public function __construct(MemberRepositoryEloquent $user)
    {
        //parent::__construct();
        $this->user = $user;

    }

    public function index($symbol){
        $option = Option::select('id','name', 'code','times','currency_name','currency_unit', 'exchange_rate',
        'fluctuation',   //最小波动值
        'fluctuation_price', //最小波动价格
        'surplus_value',    //止盈值
        'stop_loss_value',  //止损值
        'stop_loss_margin', //止损保证金
        'transaction_cost')->where('code','=',$symbol)->first();
        //get_option_data('PMAU');
        //
        //判断是否是在交易时间
        $times = $option->times;
        $times = explode(',',$times);
        $timesWhere = false;
        $endDateTime ='';
        foreach($times as $k=>$time){
            list($start,$end) = explode('-',$time);
            if($start>=$end){
                if(date("w")!=6){
                    if(date('H:i')>=$start || date('H:i',time())<=$end){
                        $timesWhere = true;
                        if(date('H:i')>=$start){
                            //mktime(hour,minute,second,month,day,year,is_dst);
                            //$endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d',strtotime("+1 day")),date('Y'));
                            $endDateTime = $end;
                        }else{
                            // $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                            $endDateTime = $end;
                        }
                        break;return;
                    }
                }else{
                    if(date('H:i',time())<=$end){
                        $timesWhere = true;
                        // $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                        $endDateTime = $end;
                        break;return;
                    }
                }
                
            }else{
                if(date('H:i')>=$start && date('H:i',time())<=$end){
                    $timesWhere = true;
                    //$endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                    $endDateTime = $end;
                    break;return;
                }else{
                    
                }
            }
        }
        //dd($endDateTime);
        //
        //
        //$times = $option->times;
        //$times = explode(',',$times);
        $newtimes = [];
        foreach($times as $k=>$time){
            list($start,$end) = explode('-',$time);
            if($start>=$end){
                //echo 1;
                $periodone = $start.'-24:00';
                $periodtwo = "00:00-".$end;
                //unset($times[$k]);
                $newtimes[] = $periodone;
                $newtimes[] = $periodtwo;
            }else{
                //echo 2;
                $newtimes[] = $time;
            }
        }
        //$times =implode(',',$times);
        $newtimes = json_encode($newtimes);
      //var_dump($newtimes);
        $optionData= get_option_data($symbol);
        $optionDate = date('Ymd',strtotime($optionData['date_time']));
        //echo $optionDate;
        if(date('Ymd')!=$optionDate || strtotime($optionData['date_time'])<$optionData['create_time']-20){
            $endDateTime = '';
            
        }
        //var_dump($optionData);
        return view('home.option.index',compact('option','newtimes','optionData','endDateTime'));
    }

    public function insert(Request $request){
        
        $user = $request->user();

        $validator = Validator::make($request->all(), [
            'option_id' => 'required|integer',
            'amount'=>'required|numeric|min:0.01',
            'direction'=>'required|integer',
            'stop_loss_value'=>'required|numeric',
            'surplus_value'=>'required|numeric',
            'stop_loss_margin'=>'required|numeric',
            'transaction_cost'=>'required|numeric',
            'hand_count'=>'required|integer',
            //'buy_point'=>'required|numeric',
            //'times'=>'required|integer',
            //'yield_rate'=>'required|numeric',
        ]);
        $option_id = $request->option_id;
        $option = Option::select('id','name', 'code','times','currency_name','currency_unit', 'exchange_rate',
        'fluctuation',   //最小波动值
        'fluctuation_price', //最小波动价格
        'surplus_value',    //止盈值
        'stop_loss_value',  //止损值
        'stop_loss_margin', //止损保证金
        'transaction_cost',
        'hand_count')->where('id','=',$option_id)->first();
        //dd($option);
        $optionData = get_option_data($option->code);
        //var_dump($optionData);
        
        //判断是否是在交易时间
        $times = $option->times;
        $times = explode(',',$times);
        $timesWhere = false;
        foreach($times as $k=>$time){
            list($start,$end) = explode('-',$time);
            if($start>=$end){
                if(date("w")!=6){
                    if(date('H:i')>=$start || date('H:i',time())<=$end){
                        $timesWhere = true;
                        if(date('H:i')>=$start){
                            //mktime(hour,minute,second,month,day,year,is_dst);
                            $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d',strtotime("+1 day")),date('Y'));
                        }else{
                            $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                        }
                        break;return;
                    }
                }else{
                    if(date('H:i',time())<=$end){
                        $timesWhere = true;
                        $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                        break;return;
                    }
                }
                
            }else{
                if(date('H:i')>=$start && date('H:i',time())<=$end){
                    $timesWhere = true;
                    $endDateTime = mktime(date('H',strtotime($end)),date('i',strtotime($end)),date('s',strtotime($end)),date('m'),date('d'),date('Y'));
                    break;return;
                }else{
                    
                }
            }
        }



        //
        
        $validator->after(function($validator) use ($option,$optionData,$user,$request,$timesWhere) {
            if (!$option) {
                $validator->errors()->add(0, '未找到有效期权合约!');
            }
            if(!$optionData || $optionData['last_price']<=0 || $optionData['buy_price']<=0 || $optionData['sell_price']<=0){
                //$validator->errors()->add(0, '休市期间，如有疑问请联系客服!');
            }

            //判断各项值是否是有效值
            $hand_count_arr = explode(',',$option['hand_count']);
            $surplus_value_arr = explode(',',$option['surplus_value']);
            $stop_loss_value_arr = explode(',',$option['stop_loss_value']);
            $stop_loss_margin_arr = explode(',',$option['stop_loss_margin']);
            $k = array_search($request['stop_loss_value'],$stop_loss_value_arr);
            if( $k===false ||
                empty($request['hand_count']) || 
                !in_array($request['hand_count'], $hand_count_arr) || 
                $request['surplus_value']!=$surplus_value_arr[$k] ||
                $request['stop_loss_margin']/$request['hand_count']!=$stop_loss_margin_arr[$k]
            ){
                // var_dump($k);
                // var_dump($surplus_value_arr[$k]);
                // var_dump($stop_loss_margin_arr[$k]);
                $validator->errors()->add(0, '数据异常,请联系客服!');
            }

            //判断是否休市
            
            $optionDate = date('Ymd',strtotime($optionData['date_time']));
            //echo $optionDate;
            if(date('Ymd')!=$optionDate || strtotime($optionData['date_time'])<$optionData['create_time']-20){
                $validator->errors()->add(0, '休市期间，如有疑问请联系客服!');
            }

            if(!$timesWhere){
                $validator->errors()->add(0, '不在交易时段，如有疑问请联系客服!');
            }

            //
            //判断余额是否足够
            if($user->balance<abs($request['amount']*$option['exchange_rate'])){
                $validator->errors()->add(0, '余额不足，请先充值!');
            }

        });

        //判断是否休市


        //
        
        if ($validator->fails()) {
            $msg=[];
            $messages  = $validator->errors();
            foreach ($messages ->all() as $message) {
                //
                $msg[0] = $message;
            }
            //$msg->status = 0;
            //return response()->json(['status'=>0,'msg'=>$msg->first()], 200);
            return response()->json(['status'=>0,'msg'=>$msg], 200);
        }

        //根据手数生成订单
        
        //dd(1);
        DB::beginTransaction();
        try{ 
            //订单编码
            $orderno = date('YmdHis').rand(1000,9999);
            //$note = $option->name.'('.$option->code.')下单，订单号:'.$orderno;
            $note = '冻结保证金('.$option->name.')';
            $result = $this->user->modifyBalance($user->id,-$request['stop_loss_margin']*$option['exchange_rate'],7,$note);
            if($result['status']){
                 $note = '交易综合费('.$option->name.')';
                $result = $this->user->modifyBalance($user->id,-$request['transaction_cost']*$option['exchange_rate'],8,$note);
            }
            //return response()->json(['status'=>1,'order'=>$result], 200);
            
            //止损 止跌点位
            if($request['direction']==1){
                $surplus_point = $optionData['last_price']+($request['surplus_value']/$option['fluctuation_price'])*$option['fluctuation'];
                $stop_loss_point = $optionData['last_price']-($request['stop_loss_value']/$option['fluctuation_price'])*$option['fluctuation'];
            }else{
                $surplus_point = $optionData['last_price']-($request['surplus_value']/$option['fluctuation_price'])*$option['fluctuation'];
                $stop_loss_point = $optionData['last_price']+($request['stop_loss_value']/$option['fluctuation_price'])*$option['fluctuation'];
            }

            $surplus_point = number_format($surplus_point,get_float_length($optionData['last_price']),".","");
            $stop_loss_point = number_format($stop_loss_point,get_float_length($optionData['last_price']),'.',"");

            if($result['status']){
                for($i=0;$i<$request['hand_count'];$i++){
                //return response()->json(['status'=>0,'msg'=>['扣款失败']], 200);
                $order = Order::create([
                    'option_id'=>$request['option_id'],
                    'orderno'=>$orderno,
                    'user_id'=>$user->id,
                    'symbol'=>$option['code'],
                    'amount'=>$request['amount'],
                    'pays'=>$request['amount'],
                    //'times'=>$request['times'],
                    'direction'=>$request['direction'],
                    'buy_point'=>$optionData['last_price'],
                    'surplus_point'=>$surplus_point,
                    'stop_loss_point'=>$stop_loss_point,
                    'surplus_value'=>$request['surplus_value'],    //止盈值
                    'stop_loss_value'=>$request['stop_loss_value'],  //止损值
                    'stop_loss_margin'=>$request['stop_loss_margin']/$request['hand_count'], //止损保证金
                    'transaction_cost'=>$request['transaction_cost']/$request['hand_count'], //综合交易费
                    'stop_loss_margin_rmb'=>($request['stop_loss_margin']/$request['hand_count'])*$option['exchange_rate'], //止损保证金
                    'transaction_cost_rmb'=>($request['transaction_cost']/$request['hand_count'])*$option['exchange_rate'], //综合交易费
                    'rate'=>$option['exchange_rate'],
                    'hand_count'=>$request['hand_count'],
                    'close_time'=>$endDateTime
                    //'rate'=>$request['yield_rate'],
                    //'close_time'=>time()+$request['times']
                ]);
                if($order){

                    //判断是否有上级
                    //$count = UserRelationship::where('subordinateid','=',$user->id)->where('level','>',0)->count();
                    $parents = null;
                    if($user->parent_id){
                        //$parent=$user->parent()->get()->first();
                        $parents=$user->ancestors()->get()->all();
                    }
                    //var_dump($parents);
                    if(!empty($parents)){
                        //dd($parent->mobile);
                        //判断上级是否有代理商
                        
                        //var_dump($maker->superior());exit;
                        $commission_rates=[];
                        //获取分佣比例，逗号分隔
                        // if($makerRelationship){
                          
                        //     $maker =$this->user->find($makerRelationship->superiorid);
                        //     $commission_rates = explode(',',$maker->commission_rate);
                        // }

                        if(empty($commission_rates)){
                            $commission_rates = Config::get('system.commission_rate');
                        }
                        //var_dump($commission_rates);
                        foreach($commission_rates as $k=>$rate){
                            //echo $k;
                            if($k>=count($parents)){
                                break;return;
                            }
                            $parents = array_reverse($parents);
                            $parent = $parents[$k];
                            //var_dump($agent);
                            //var_dump($agent);
                            if(!empty($parent) && $parent->is_agent){
                                $commission = ($request['transaction_cost']/$request['hand_count'])*$option['exchange_rate']*$rate;
                                Commission::create([
                                    'order_user_id'=>$user->id,
                                    'commission_user_id'=>$parent->id,
                                    'orderno'=>$orderno,                           
                                    'amount'=>($request['transaction_cost']/$request['hand_count'])*$option['exchange_rate'],
                                    'commission'=>$commission,
                                    'commission_user_level'=>$k+1,
                                    'note'=>'用户'.$user->name.'('.$user->mobile.')下单佣金'
                                ]);
                            }
                            
                        }
                                                    
                    }
                    $user = User::find($user->id);
                    $return =  response()->json(['status'=>1,'user'=>$user], 200);
                }else{
                    $return = response()->json(['status'=>0,'msg'=>['下单失败']], 200);
                }
                }
            }else{
                $return = response()->json(['status'=>0,'msg'=>[$result['msg']]], 200);
            }    
            
            
            
            
            //中间逻辑代码 
            DB::commit(); 
            return $return;
        }catch (\Exception $e) { 
            //接收异常处理并回滚 
            //var_dump($e);
            DB::rollBack(); 
            return response()->json(['status'=>0,'msg'=>['系统异常，下单失败']], 200);
        }

        
        
       //return response()->json(['status'=>1,'order'=>1], 200);
        

    }

    /**
     * [position 持仓订单]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function position(Request $request,$option_id){
        $user = $request->user();
        //获取持仓数据
        $orders = Order::where('user_id','=',$user->id)
                ->where('option_id','=',$option_id)
                //->where('close_time','>',time())
                ->where('status','=','0')
                ->get();
        foreach($orders as $k=>$order){
            $countdown = $order->close_time-time();
            $order->countdown = $countdown;
            $option_name = $order->option->name;
            $order->option_name = $option_name;
        }
        return response()->json($orders);
    }

    /**
     * [settlement 结算订单]
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function settlement(Request $request,$option_id){
        $user = $request->user();
        //获取持仓数据
        $orders = Order::where('user_id','=',$user->id)
                ->where('option_id','=',$option_id)
                ->where('status','>','0')
                ->orderBy('id','desc')
                ->paginate(5);
        foreach($orders as $k=>$order){
            $option_name = $order->option->name;
            $order->option_name = $option_name;
            $order->close_time = date('Y-m-d H:i:s',$order->close_time);
        }
        $user = User::find($user->id);
        return response()->json(['orders'=>$orders,'user'=>$user]);
    }

    /**
     * [unwind 平仓]
     * @param  Request $request [description]
     * @param  [type]  $id      [订单ID]
     * @return [type]           [description]
     */
    public function unwind(Request $request){
        $id = $request->id;
        $user = $request->user();
        //获取持仓数据
        $order = Order::where('user_id','=',$user->id)
                ->where('id','=',$id)
                ->where('status','=','0')
                ->first();
        if(!$order){
            return response()->json(['status'=>0,'msg'=>['订单数据异常']], 200);
        }

        //获取订单行情
        $optionData = get_option_data($order->symbol);
        if($order->direction==1){
            if($optionData['last_price'] >= $order->surplus_point){
                $optionData['last_price'] = $order->surplus_point;
            }

            if($optionData['last_price'] <= $order->stop_loss_point){
                $optionData['last_price'] = $order->stop_loss_point;
            }
        }else{
            if($optionData['last_price'] <= $order->surplus_point){
                $optionData['last_price'] = $order->surplus_point;
            }

            if($optionData['last_price'] >= $order->stop_loss_point){
                $optionData['last_price'] = $order->stop_loss_point;
            }
        }

        $spread = $optionData['last_price'] - $order->buy_point;
        $profit = $spread/$order->option->fluctuation*$order->option->fluctuation_price;

        if($order->direction==0){
            if($profit<0){//点数上涨
                $profit = abs($profit);
            }else{
                $profit = -abs($profit);
            }
        }

        $profit = $profit*$order->option->exchange_rate;
        //更改订单状态
        $order->close_point = $optionData['last_price'];
        $order->profit = $profit;
        $order->close_time = time();
        $order->status = 1;
        if(!$order->save()){
            return response()->json(['status'=>0,'msg'=>['平仓失败']], 200);
        }

       // $note = '解冻保证金('.$order->option->name.')';
        $note = '解冻保证金('.$order->option->name.')['.$order->id.']';
        $result = $this->user->modifyBalance($user->id,$order->stop_loss_margin*$order->option->exchange_rate,9,$note);
        if($result['status']){
            //$note = '订单结算('.$order->option->name.')';
            $note = '订单结算('.$order->option->name.')['.$order->id.']';
            $result = $this->user->modifyBalance($user->id,$profit,10,$note);
        }

        if($result['status']){
            $user = User::find($user->id);
            $return =  response()->json(['status'=>1,'user'=>$user], 200);
            
        }else{
            $return = response()->json(['status'=>0,'msg'=>[$result['msg']]], 200);
        }
        

        return $return;
    }


    public function unwindall(Request $request){
        $option_id = $request->option_id;
        $user = $request->user();
        //获取持仓数据
        $orders = Order::where('option_id','=',$option_id)
                ->where('user_id','=',$user->id)
                ->where('status','=','0')
                ->get();
        //dd($orders->all());
        if(!$orders->all()){
            return response()->json(['status'=>0,'msg'=>['没有订单可平仓！']], 200);
        }

        $option = Option::select('id','name', 'code')->where('id','=', $option_id)->first();

        $optionData = get_option_data($option->code);

        

        foreach($orders as $k=>$order){
            //获取订单行情
           
            if($order->direction==1){
                if($optionData['last_price'] >= $order->surplus_point){
                    $optionData['last_price'] = $order->surplus_point;
                }

                if($optionData['last_price'] <= $order->stop_loss_point){
                    $optionData['last_price'] = $order->stop_loss_point;
                }
            }else{
                if($optionData['last_price'] <= $order->surplus_point){
                    $optionData['last_price'] = $order->surplus_point;
                }

                if($optionData['last_price'] >= $order->stop_loss_point){
                    $optionData['last_price'] = $order->stop_loss_point;
                }
            }

            $spread = $optionData['last_price'] - $order->buy_point;
            $profit = $spread/$order->option->fluctuation*$order->option->fluctuation_price;

            if($order->direction==0){
                if($profit<0){//点数上涨
                    $profit = abs($profit);
                }else{
                    $profit = -abs($profit);
                }
            }

            $profit = $profit*$order->option->exchange_rate;
            //更改订单状态
            $order->close_point = $optionData['last_price'];
            $order->profit = $profit;
            $order->close_time = time();
            $order->status = 1;
            if(!$order->save()){
                $return = response()->json(['status'=>0,'msg'=>['平仓失败']], 200);
                continue;
            }

            //$note = '解冻保证金('.$order->option->name.')';
            $note = '解冻保证金('.$order->option->name.')['.$order->id.']';
            $result = $this->user->modifyBalance($user->id,$order->stop_loss_margin*$order->option->exchange_rate,9,$note);
            if($result['status']){
                //$note = '订单结算('.$order->option->name.')';
                $note = '订单结算('.$order->option->name.')['.$order->id.']';
                $result = $this->user->modifyBalance($user->id,$profit,10,$note);
            }

            // if($result['status']){
            //     $user = User::find($user->id);
            //     $return =  response()->json(['status'=>1,'user'=>$user], 200);
                
            // }
        }
        $user = User::select('name','balance')->find($user->id);
        if(!isset($return)){
             $return =  response()->json(['status'=>1,'user'=>$user], 200);
        }
        return $return;

    }

}